package cn.wolfcode.controller;

import cn.wolfcode.Utils.CharUtil;
import cn.wolfcode.domain.Business;
import cn.wolfcode.query.BusinessQueryObject;
import cn.wolfcode.result.JsonResult;
import cn.wolfcode.service.IBusinessService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") BusinessQueryObject qo, Model model){

        PageInfo<Business> pageInfo = businessService.list(qo);
        model.addAttribute("result",pageInfo);

        return "business/list";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model){
        if (id==null){

        }else {
              Business business =businessService.selectByPrimaryKey(id);
              model.addAttribute("currentBusiness",business);
        }
        return "business/input";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Business business,Long id){
        //if (business.getLegal_name()==null) {
            businessService.deleteByPrimaryKey(id);
            return JsonResult.success(null);
        //}
        //return JsonResult.error("门店下有客户，不能进行删除！");
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(MultipartFile file, Business business,
                               HttpServletRequest request)throws Exception{
        //处理老照片
        if (business.getId()!=null){
            String oldimg = business.getLicense_img();
            String path = request.getServletContext().getRealPath("/");
            File oldFile = new File(path+oldimg);
            oldFile.delete();
        }
        //1.处理上传图片
        String filename = file.getOriginalFilename();
        String[] arr = filename.split("\\.");
        //获取文件的扩展名
        String ext = arr[arr.length-1];
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String sdate = sdf.format(date);
        int rand = (int)(Math.random()*89999+10000);
        StringBuilder sb = new StringBuilder();
        sb.append(sdate);
        sb.append(rand);
        sb.append(".");
        sb.append(ext);
        String newFilename = sb.toString();
        //图片上传的位置:webapp中的img目录
        //找到img目录的路径
        String realPath = request.getServletContext().getRealPath("/img/");
        File newFile = new File(realPath, newFilename);
        FileOutputStream outputStream = new FileOutputStream(newFile);
        InputStream inputStream = file.getInputStream();
        //读取数据的容器
        byte[] buf = new byte[100];
        //每次读取的长度
        int len = 0;
        while ((len = inputStream.read(buf)) != -1){
            outputStream.write(buf,0,len);
        }
        outputStream.close();

        //2.将图片地址添加到business对象中
        business.setLicense_img("/img/"+newFilename);

        //3.处理文件中文乱码
        CharUtil.convert(business,Business.class);

        //4.持久化business对象
        if (business.getId()==null){
            businessService.insert(business);
        }else {
            businessService.updateByPrimaryKey(business);
        }
        return "redirect:/business/list";
    }
}
